<template>
  <div class="meeting-room-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>会议室管理</h2>
          <el-button type="primary" @click="dialogVisible = true">添加会议室</el-button>
        </div>
      </template>

      <!-- 查询区域 -->
      <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 20px">
        <el-input
          v-model="searchName"
          placeholder="请输入会议室名称"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter="handleSearch"
        />
        <el-select
          v-model="selectedEquipments"
          multiple
          clearable
          collapse-tags
          placeholder="请选择设备"
          size="small"
          style="width: 220px"
        >
          <el-option label="投影仪" value="hasProjector" />
          <el-option label="音响系统" value="hasSoundSystem" />
          <el-option label="网络" value="hasNetwork" />
        </el-select>
        <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>

      <!-- 会议室列表表格 -->
      <el-table :data="filteredMeetingRooms" style="width: 100%" border stripe>
        <el-table-column prop="roomId" label="ID" width="80" />
        <el-table-column prop="name" label="会议室名称" width="120" />
        <!-- 修改类型列的显示 -->
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag size="small" :type="getTypeColor(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="seats" label="容量" width="100">
          <template #default="scope">
            <el-tag size="small" :type="getSeatsType(scope.row.seats)">
              {{ scope.row.seats }} 人
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="设备" width="200">
          <template #default="scope">
            <el-space wrap>
              <el-tag v-if="scope.row.hasProjector" size="small" type="success"> 投影仪 </el-tag>
              <el-tag v-if="scope.row.hasSoundSystem" size="small" type="success">
                音响系统
              </el-tag>
              <el-tag v-if="scope.row.hasNetwork" size="small" type="success"> 网络 </el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="pricePerHour" label="每小时价格" width="100">
          <template #default="scope"> ¥{{ scope.row.pricePerHour }} </template>
        </el-table-column>
        <el-table-column prop="areaSqm" label="面积(㎡)" width="100">
          <template #default="scope"> {{ scope.row.areaSqm }}㎡ </template>
        </el-table-column>
        <el-table-column prop="otherEquipmentDetails" label="设备说明" width="180">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.otherEquipmentDetails"
              :content="scope.row.otherEquipmentDetails"
            >
              <span
                >{{ scope.row.otherEquipmentDetails.substring(0, 10)
                }}{{ scope.row.otherEquipmentDetails.length > 10 ? '...' : '' }}</span
              >
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="180">
          <template #default="scope">
            <el-tooltip v-if="scope.row.description" :content="scope.row.description">
              <span
                >{{ scope.row.description.substring(0, 10)
                }}{{ scope.row.description.length > 10 ? '...' : '' }}</span
              >
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加会议室对话框 -->
    <el-dialog v-model="dialogVisible" title="添加会议室" width="50%">
      <el-form :model="newRoom" label-width="120px">
        <el-form-item label="会议室名称" required>
          <el-input v-model="newRoom.name" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="newRoom.type" placeholder="请选择会议室类型">
            <el-option label="教室型" value="CLASSROOM_STYLE" />
            <el-option label="圆桌型" value="ROUND_TABLE_STYLE" />
          </el-select>
        </el-form-item>
        <el-form-item label="容量" required>
          <el-input-number v-model="newRoom.seats" :min="1" />
        </el-form-item>
        <el-form-item label="面积(㎡)" required>
          <el-input-number v-model="newRoom.areaSqm" :min="1" :max="1000" :precision="2" />
        </el-form-item>
        <el-form-item label="设备">
          <el-checkbox-group v-model="newRoom.equipment">
            <el-checkbox label="hasProjector">投影仪</el-checkbox>
            <el-checkbox label="hasSoundSystem">音响系统</el-checkbox>
            <el-checkbox label="hasNetwork">网络</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="设备说明">
          <el-input
            v-model="newRoom.otherEquipmentDetails"
            type="textarea"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newRoom.description"
            type="textarea"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="每小时价格" required>
          <el-input-number v-model="newRoom.pricePerHour" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑会议室对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑会议室" width="50%">
      <el-form v-if="editingRoom" :model="editingRoom" label-width="120px">
        <el-form-item label="会议室名称" required>
          <el-input v-model="editingRoom.name" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="editingRoom.type" placeholder="请选择会议室类型">
            <el-option label="教室型" value="CLASSROOM_STYLE" />
            <el-option label="圆桌型" value="ROUND_TABLE_STYLE" />
          </el-select>
        </el-form-item>
        <el-form-item label="容量" required>
          <el-input-number v-model="editingRoom.seats" :min="1" />
        </el-form-item>
        <el-form-item label="面积(㎡)" required>
          <el-input-number v-model="editingRoom.areaSqm" :min="1" :max="1000" :precision="2" />
        </el-form-item>
        <el-form-item label="设备">
          <el-checkbox v-model="editingRoom.hasProjector">投影仪</el-checkbox>
          <el-checkbox v-model="editingRoom.hasSoundSystem">音响系统</el-checkbox>
          <el-checkbox v-model="editingRoom.hasNetwork">网络</el-checkbox>
        </el-form-item>
        <el-form-item label="设备说明">
          <el-input
            v-model="editingRoom.otherEquipmentDetails"
            type="textarea"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editingRoom.description"
            type="textarea"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="每小时价格" required>
          <el-input-number v-model="editingRoom.pricePerHour" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="editingRoom.status" placeholder="请选择状态">
            <el-option label="空闲中" value="AVAILABLE" />
            <el-option label="使用中" value="IN_USE" />
            <el-option label="维护中" value="MAINTENANCE" />
            <el-option label="已预订" value="BOOKED" />
            <el-option label="锁定中" value="LOCKED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditedRoom">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const meetingRooms = ref([])
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const loading = ref(false)
const searchName = ref('')
const selectedEquipments = ref([])
const searchKey = ref('')
const newRoom = ref({
  name: '',
  type: 'CLASSROOM_STYLE', // 设置默认类型
  seats: 1,
  areaSqm: 0.0,
  equipment: [],
  hasProjector: false,
  hasSoundSystem: false,
  hasNetwork: false,
  otherEquipmentDetails: '',
  description: '',
  pricePerHour: 0,
  status: 'AVAILABLE', // 设置默认状态
})
const editingRoom = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 添加类型标签映射
const getTypeLabel = (type) => {
  const typeMap = {
    CLASSROOM_STYLE: '教室型',
    ROUND_TABLE_STYLE: '圆桌型',
    // 如果后端返回的是中文，则保持映射
    教室型: '教室型',
    圆桌型: '圆桌型',
  }
  return typeMap[type] || type
}

// 获取类型标签颜色
const getTypeColor = (type) => {
  return type === 'CLASSROOM_STYLE' || type === '教室型' ? 'primary' : 'success'
}

// 获取容量标签颜色
const getSeatsType = (seats) => {
  if (seats <= 10) return 'info'
  if (seats <= 20) return ''
  return 'warning'
}

// 修改状态标签映射
const getStatusLabel = (status) => {
  const statusMap = {
    AVAILABLE: '空闲中',
    IN_USE: '使用中',
    MAINTENANCE: '维护中',
    BOOKED: '已预订',
    LOCKED: '锁定中',
    // 中文映射保持不变
    空闲中: '空闲中',
    使用中: '使用中',
    维护中: '维护中',
    已预订: '已预订',
    锁定中: '锁定中',
  }
  return statusMap[status] || status
}

// 修改状态类型映射
const getStatusType = (status) => {
  const types = {
    AVAILABLE: 'success',
    LOCKED: 'warning',
    BOOKED: 'info',
    IN_USE: 'primary',
    MAINTENANCE: 'danger',
    // 如果后端返回的是中文状态，则保持以下映射
    空闲: 'success',
    锁定: 'warning',
    预定: 'info',
    使用: 'primary',
    维护: 'danger',
  }
  return types[status] || 'info'
}

const handleSearch = () => {
  searchKey.value = searchName.value.trim()
  currentPage.value = 1 // 重置到第一页
}

const resetSearch = () => {
  searchName.value = ''
  searchKey.value = ''
  selectedEquipments.value = []
  currentPage.value = 1 // 重置到第一页
}

const filteredMeetingRooms = computed(() => {
  let rooms = meetingRooms.value

  // 搜索过滤
  if (searchKey.value) {
    rooms = rooms.filter(
      (room) => room.name && room.name.toLowerCase().includes(searchKey.value.toLowerCase())
    )
  }

  // 设备过滤
  if (selectedEquipments.value.length > 0) {
    rooms = rooms.filter((room) => selectedEquipments.value.every((eq) => room[eq]))
  }

  // 更新总数
  total.value = rooms.length

  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value

  return rooms.slice(startIndex, endIndex)
})

// 添加分页处理方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理编辑
const handleEdit = (room) => {
  editingRoom.value = { ...room }
  editDialogVisible.value = true
}

// 处理删除
const handleDelete = (room) => {
  ElMessageBox.confirm('确定要删除该会议室吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteRoom(room.roomId)
    })
    .catch(() => {})
}

// 获取会议室列表
const fetchMeetingRooms = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/meetingrooms')
    meetingRooms.value = response.data
    total.value = response.data.length // 更新总数
  } catch (error) {
    console.error('Error fetching meeting rooms:', error)
    ElMessage.error('获取会议室列表失败')
  } finally {
    loading.value = false
  }
}

// 添加会议室
const addRoom = async () => {
  try {
    const roomData = {
      ...newRoom.value,
      hasProjector: newRoom.value.equipment?.includes('hasProjector') || false,
      hasSoundSystem: newRoom.value.equipment?.includes('hasSoundSystem') || false,
      hasNetwork: newRoom.value.equipment?.includes('hasNetwork') || false,
    }
    delete roomData.equipment

    const response = await axios.post('http://localhost:8080/api/meetingrooms', roomData)

    if (response.data) {
      ElMessage.success('会议室添加成功！')
      newRoom.value = {
        name: '',
        type: '',
        seats: 1,
        equipment: [],
        hasProjector: false,
        hasSoundSystem: false,
        hasNetwork: false,
        pricePerHour: 0,
        status: '空闲',
      }
      await fetchMeetingRooms() // 重新获取数据
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('Error adding meeting room:', error)
    ElMessage.error(error.response?.data?.message || '添加会议室时发生错误！')
  }
}

// 删除会议室
const deleteRoom = async (roomId) => {
  try {
    const response = await axios.delete(`http://localhost:8080/api/meetingrooms/${roomId}`)

    if (response.data) {
      ElMessage.success('会议室删除成功！')
      meetingRooms.value = meetingRooms.value.filter((room) => room.roomId !== roomId)
    } else {
      ElMessage.error('删除会议室失败！')
    }
  } catch (error) {
    console.error('Error deleting meeting room:', error)
    ElMessage.error(error.response?.data?.message || '删除会议室时发生错误！')
  }
}

// 保存编辑的会议室
const saveEditedRoom = async () => {
  try {
    const response = await axios.put('http://localhost:8080/api/meetingrooms', editingRoom.value)

    if (response.data) {
      ElMessage.success('会议室更新成功！')
      editingRoom.value = null
      await fetchMeetingRooms()
      editDialogVisible.value = false
    } else {
      ElMessage.error('更新会议室失败！')
    }
  } catch (error) {
    console.error('Error saving edited room:', error)
    ElMessage.error(error.response?.data?.message || '更新会议室时发生错误！')
  }
}

// 修改挂载时的调用
onMounted(() => {
  fetchMeetingRooms()
})
</script>

<style scoped>
.meeting-room-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.el-button-group .el-button {
  margin-left: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
